/**
 *
 */
package hichecker.ui.custom_views.series;

import hichecker.controller.Config;
import hichecker.ui.components.custom_table.AbstractCustomTableModel;
import hichecker.ui.components.custom_table.column_class.Points;
import hichecker.university.Series;
import hichecker.university.Task;

import java.util.List;

/**
 *
 */
public class SeriesSettingsTableModel extends AbstractCustomTableModel<String> {

	private List<Task> tasks;

	/**
	 *
	 */
	public SeriesSettingsTableModel(Series series) {
		tasks = series.getTasks();
	}

	@Override
	protected String getRowID(int row) {
		return tasks == null || tasks.size() <= row ? null : "" + tasks.get(row).hashCode();
	}

	@Override
	public Object getValueAt(int row, int column) {
		if (row == getRowCount() - 1)
			return null;
		Task curTask = tasks.get(row);
		switch (column) {
			case 0: return curTask.getName();
			case 1: return curTask.getMaxPoints();
			case 2: return curTask.isOptional();
			default: return null;
		}
	}

	@Override
	public void setValueAt(Object value, int row, int column) {
		// Neue Zeile geändert
		boolean lastLine = row >= tasks.size();
		if (lastLine) {
			addRow();
		}

		Task curTask = tasks.get(row);
		switch (column) {
		case 0:
			curTask.setName("" + value);
			break;
		case 1:
			("" + value).replace(",", ".");
			curTask.setMaxPoints(Math.round(Float.parseFloat("" + value) * 10) / 10f);
			break;
		case 2:
			curTask.setOptional((Boolean) value);
		}
	}

	public void addRow() {
		tasks.add(new Task());
		fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
	}

	public void deleteRow(int row) {
		if (row < tasks.size()) {
			tasks.remove(row);
			fireTableRowsDeleted(row, row);
		}
	}


	@Override
	public int getColumnCount() {
		return 3;
	}

	@Override
	public int getRowCount() {
		return tasks.size() + 1;
	}

	@Override
	public Class<?> getColumnClass(int column) {
		switch (column) {
			case 0: return Object.class;
			case 1: return Points.class;
			case 2: return Boolean.class;
			default: return Object.class;
		}
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return true;
	}

	@Override
	public Object[] getHeaderValues() {
		headerValues = new Object[getColumnCount()];

		headerValues[0] = Config.TASK_NAME;
		headerValues[1] = Config.TASK_MAX;
		headerValues[2] = Config.TASK_OPTIONAL;

		return headerValues;
	}

}
